package com.neihe.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 */
@Configuration
public class ThreadPoolConfig {

    @Bean("mailAsyncThread")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 获取CPU核心数
        int cpuCores = Runtime.getRuntime().availableProcessors();
        // 核心线程数 = CPU核心数 + 1
        executor.setCorePoolSize(cpuCores + 1);
        // 最大线程数 = CPU核心数 * 2 + 1
        executor.setMaxPoolSize(cpuCores * 2 + 1);
        // 线程空闲时间
        executor.setKeepAliveSeconds(60);
        // 工作队列容量 = CPU核心数 * 50（可根据实际情况调整）
        executor.setQueueCapacity(cpuCores * 50);
        // 线程名前缀
        executor.setThreadNamePrefix("event-listener-thread");
        // 配置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
